package com.java.advance.ticket.service.impl;

import com.java.advance.ticket.dao.TicketMapper;
import com.java.advance.ticket.redis.RedisManager;
import com.java.advance.ticket.redis.key.TicketKey;
import com.java.advance.ticket.service.ITicketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by yangminghua on 2019/4/16.
 */
@Slf4j
@Service("ticketService")
public class TicketServiceImpl implements ITicketService {

    @Autowired
    TicketMapper ticketMapper;

    @Resource(name = "RedisManager")
    RedisManager redisManager;

    @Override
    public Object queryTicketStock(String ticketSeq) {
        log.info("ticketSeq:{}", ticketSeq);
        //1、先从缓存中获取该车次的余票信息
        Integer stock = redisManager.get(TicketKey.queryTicketStock, ticketSeq, Integer.class);
        log.info("stock:{}", stock);
        if (stock != null) {
            log.info("从缓存获取数据成功");
            return stock;
        }
        //2、缓存中没有则取数据库
        stock = ticketMapper.selectByPrimaryKey(ticketSeq).getTicketStock();
        log.info("从数据库获取数据成功");
        //3、塞到缓存当中，120秒过期
        redisManager.set(TicketKey.queryTicketStock, ticketSeq, stock);
        //4、返回
        return stock;
    }
}
